<template>
  <div>
    <div class="song" ref="song">
      <!-- lorem是乱数假文，又叫做哑元文本，或者无意义文本，在印刷及排版领域广泛使用。lorem后面接数字表示几个单词 
    -->
      <!-- ul>li*30>lorem3 -->
      <ul ref="ul">
        <li
          v-for="(item, index) in songList"
          :key="item.id"
          :index="index"
          :class="{ active: index === activeIndex }"
          @click="onClick(index)"
        >
          {{ item.sentence }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Mock from "mockjs"; // 引入mockjs

export default {
  name: "song",
  data() {
    return {
      songList: [], // 歌词
      activeIndex: 0, // 激活索引
      boxHeight: 0, // 盒子高度
      ulHeight: 0, // ul高度
      liHeight: 0, // li高度
    };
  },
  mounted() {
    this.getSongList(); // 生成歌词数据
  },
  methods: {
    // 监听点击事件
    onClick(index) {
      this.activeIndex = index;
      this.scrollSong();
    },
    //获取对应盒子的高度
    getBoxHeight() {
      const box = this.$refs.song;
      this.boxHeight = box.clientHeight;
      const ul = this.$refs.ul;
      this.ulHeight = ul.clientHeight;
      const li = ul.children[0];
      this.liHeight = li.clientHeight;
      console.log(this.boxHeight, this.ulHeight, this.liHeight);
    },
    // 滚动歌词
    scrollSong() {
      console.log("滚动歌词");
      //防止重复获取对应的数据，只需要获取一次就可以了
      if (!this.boxHeight) {
        this.getBoxHeight();
      }
      let scrollHeight =
        this.liHeight * this.activeIndex +
        this.liHeight / 2 -
        this.boxHeight / 2;
      scrollHeight = -scrollHeight;
      // 如果滚动高度大于ul高度减去盒子高度，则将滚动高度设置为ul高度减去盒子高度
      // 滚动到最后几个的时候就不让其滚动到中间
      if (scrollHeight > this.ulHeight - this.boxHeight) {
        scrollHeight = this.ulHeight - this.boxHeight;
      }

      this.$refs.ul.style.transform = `translateY(${scrollHeight}px)`;
    },
    // 生成歌词数据
    getSongList() {
      for (let i = 0; i < 30; i++) {
        const mockData = {
          id: Mock.Random.id(), // 生成随机ID
          //生成一句话(中文)
          sentence: Mock.Random.csentence(5, 15),
          //生成一句话(英语)
          // sentence: Mock.Random.sentence(5, 10),
        };
        this.songList.push(mockData);
      }
      // console.log(this.songList);
    },
  },
};
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}
.song {
  height: 330px; // 高度
  background-color: #666; // 背景颜色
  text-align: center; // 文本居中
  overflow: hidden;
  ul {
    cursor: pointer;
    list-style: none;
    flex-wrap: nowrap; // 不换行
    transition: 0.2s; // 过渡
    li {
      box-sizing: border-box;
      height: 30px;
      // border: 1px solid #000; // 边框
      line-height: 30px; // 行高
      font-size: 18px; // 字体大小
      transition: 0.2s;
      &.active {
        color: #fff;
        transform: scale(1.5); // 缩放
      }
    }
  }
}
</style>